package com.tjetc.udp;

import java.io.IOException;
import java.net.*;

public class _2Receive {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        // 接收数据
        byte[] bytes = new byte[1024];

        // 发送和接收都是一个数据包对象
        // 通过构造器的不同方式来决定是发送还是接收
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

        System.out.println("正在等待接收.....");
        // 接收到后 datagramPacket对象中就会有数据 这里会有阻塞
        datagramSocket.receive(datagramPacket);

        System.out.println("datagramPacket.getLength() = " + datagramPacket.getLength());
        System.out.println("datagramPacket.getData() = " + new String(datagramPacket.getData(), 0, datagramPacket.getLength()));

        datagramSocket.close();
    }
}
